package com.zx.dsptuneup_cloud.Tools;

import android.util.Log;

import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 处理订单接口的任务，每个任务类处理一种接口
 *
 * @author Logen
 */

public class AsyncTask extends Thread {
    private final String TAG = "AsyncTask";

    private AsyncTask() {
    }

    static class AsyncTaskFactory {
        private final static AsyncTask instance = new AsyncTask();
    }

    // 将getInstance()方法加上同步锁
    public static synchronized AsyncTask getInstance() {
        return AsyncTaskFactory.instance;
    }

    private boolean running = true;

    public void setRunning(boolean running) {
        this.running = running;
    }

    @Override
    public void run() {
        List<String> stringList = new ArrayList<>();
        stringList.clear();
        while (running) {

            try {
              DatagramSocket datagramSocket = null;
                DatagramPacket datagramPacket = null;
                try {
                    if (datagramSocket == null) {
                        datagramSocket = new DatagramSocket(null);
                        datagramSocket.setReuseAddress(true);
                        datagramSocket.setBroadcast(true);
                        datagramSocket.bind(new InetSocketAddress(5288));
                    }
                    byte[] bytes = new byte[1024];
                    datagramPacket = new DatagramPacket(bytes, bytes.length);
                    datagramSocket.receive(datagramPacket);
                    String str = ByteToString.byteArrayToHexString(datagramPacket.getData()).toUpperCase();

              Log.d(TAG, datagramPacket.getAddress().getHostAddress() + "=====" + str);
                    String prefix = str.substring(0, 8);//协议头
                    String target = str.substring(8, 12);//目标地址

                    String order1 = str.substring(24, 28);//指令
                    String dataLengthStr = str.substring(28, 32);
                    int dataLength = ByteToString.strTo10(str.substring(28, 32));//数据长度
                   // String suffix = str.substring(dataLength + 40, dataLength + 8);//协议尾
                   // Log.d(TAG, suffix + "=====" + str);
                    //  String aa = suffix ;
               /*     if ("192.168.1.56".equals(datagramPacket.getAddress().getHostAddress())) {*/
                        if ("4810".equals(str.substring(12, 16)) /*|| "4810".equals(str.substring(8, 12))*/) {
                            //   Log.d(TAG, datagramPacket.getAddress().getHostAddress() + "=====指令" + str.substring(24, 28) + "数据包" + ByteToString.byteArrayToHexString(datagramPacket.getData()).toUpperCase());
                            Hawk.put("ip", datagramPacket.getAddress().getHostAddress());
                            if ("4101".equals(str.substring(24, 28))) {
                                stringList.add(str);
                                Log.d(TAG, datagramPacket.getAddress().getHostAddress() + "=====指令" + str.substring(24, 28) + "数据包" + ByteToString.byteArrayToHexString(datagramPacket.getData()).toUpperCase());
                            }
                        }
                        //判断头与尾是否符合
                        if ("2E437669".equals(prefix)/* && "656E642E".equals(suffix)*/ /*&& (("0001".equals(target)) || "FFFF".equals(target))*/) {
                            String source = str.substring(12, 16);//原设备地址
                            String groupHex = str.substring(16, 20);
                            Hawk.put("groupHex", groupHex);//储存16进制编组号
                            Integer group = NumberBaseConversionUtil.valueHexToValueTen(groupHex);//设备组编号
                            String level = str.substring(20, 24);//优先级
                            String order = str.substring(24, 28);//指令

                            String lenHex = str.substring(28, 32);
                            Integer len = NumberBaseConversionUtil.valueHexToValueTen(lenHex);
                            String hexData = str.substring(32, str.length() - 8);
                            if ("4810".equals(source)) {//音频处理器
                                Hawk.put("ip", datagramPacket.getAddress().getHostAddress());
                                //  to4810(group, level, order, str, DeviceConstants.deviceType.AUDIO_PROCESSING.getCode());
                                to4810(group, level, order, str);
                            } else if ("4810".equals(target)) {

                            }

                            /*else if ("5110".equals(source)) {//桌麦
                                // to4810(group, level, order, hexData, DeviceConstants.deviceType.TABLE_WHEAT.getCode());
                            } else if ("5111".equals(source)) {//掉麦处理器
                                // to4810(group, level, order, hexData, DeviceConstants.deviceType.HANGING_WHEAT.getCode());
                            }*/
                        }
                    datagramSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    private void to4810(Integer group, String level, String order, String hexData) {
        Log.d("fgswrt22", "order=" + order);
        switch (order) {
            case "7706"://设备编组信息
                // deviceGroupInfo(hexData, dType);
                deviceGroupInfo(hexData);
                System.out.println("7706-" + group);
                break;
            case "0002"://设备状态
                System.out.println("0002-" + group);
                deviceStateInfo(group, hexData);
                break;
            case "4101"://输入通道数据
                System.out.println("4101-" + group);
                deviceInputInfo(group, hexData);
                break;
            case "4103"://输出通道数据
                System.out.println("4103-" + group);
                deviceOutputInfo(group, hexData);
                break;
            case "4105"://音频矩阵数据
                System.out.println("4105-" + group);
                deviceAudioMatrixInfo(group, hexData);
                break;
            case "4107"://高低音数据
                System.out.println("4107-" + group);
                deviceHigh_low_volumeInfo(group, hexData);
                break;
            case "4109"://远程数据 00本地，01远程
                System.out.println("4109-" + group);
                deviceRemoteInfo(group, hexData);
                break;
            case "410B"://回复设置音频处理器输入参数
                System.out.println("410B-" + group);
                setResponseInputInfo(group, hexData);
                break;
            case "410D"://回复设置音频处理器输出参数
                System.out.println("410D-" + group);
                setResponseOutputInfo(group, hexData);
                break;
            case "410F"://回复设置音频处理器矩阵
                System.out.println("410F-" + group);
                setResponseAudioMatrixInfo(group, hexData);
                break;
            case "4111"://回复设置音频处理器高低音数据
                System.out.println("4111-" + group);
                setResponseHigh_low_volumeInfo(group, hexData);
                break;
            case "4113"://回复设置音频处理器REMOTE
                System.out.println("4113-" + group);
                setResponseRemoteInfo(group, hexData);
                break;
            case "4115"://回复设置音频处理器基音频端口
                System.out.println("4113-" + group);
                setResponseBasePortInfo(group, hexData);
                break;
            default:
                System.out.println("default-" + group);
                break;
        }
    }

    private void setResponseBasePortInfo(Integer group, String hexData) {
        System.out.println("基音频端口参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseBasePort_" + group, hexData, 1000);
    }

    private void setResponseRemoteInfo(Integer group, String hexData) {
        System.out.println("远程参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseRemote_" + group, hexData, 1000);
    }

    private void setResponseHigh_low_volumeInfo(Integer group, String hexData) {
        System.out.println("音频矩阵参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseHigh_low_volume_" + group, hexData, 1000);
    }

    private void setResponseAudioMatrixInfo(Integer group, String hexData) {
        System.out.println("音频矩阵参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseAudioMatrix_" + group, hexData, 1000);
    }

    private void setResponseOutputInfo(Integer group, String hexData) {
        System.out.println("输出参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseOutput_" + group, hexData, 1000);
    }

    private void setResponseInputInfo(Integer group, String hexData) {
        System.out.println("输入参数回复-" + hexData);
        ConcurrentHashMapUtil.put("responseInput_" + group, hexData, 1000);
    }

    private void deviceRemoteInfo(Integer group, String hexData) {
        Integer remote = NumberBaseConversionUtil.valueHexToValueTen(hexData);
   /*     DeviceModelVo vo = (DeviceModelVo) ConcurrentHashMapUtil.get("deviceModel_"+group);
        if (vo != null){
            vo.setRemote(remote);
            ConcurrentHashMapUtil.put("deviceModel_"+group,vo,30000);
        }*/
    }

    private void deviceHigh_low_volumeInfo(Integer group, String hexData) {
    }

    private void deviceAudioMatrixInfo(Integer group, String hexData) {

    }

    private void deviceOutputInfo(Integer group, String hexData) {
/*//        System.out.println("输出通道-"+hexData);
        String channelNoHex = hexData.substring(0, 2);
        Integer channelNo = NumberBaseConversionUtil.valueHexToValueTen(channelNoHex);
        List<Line> lines = new ArrayList<>();
        for (int i = 0; i < 10; i++){
            Line line = getLine(i,hexData);
            lines.add(line);
        }
        String muteHex = hexData.substring(hexData.length() - 6, hexData.length() - 4);
        String volumeHex = hexData.substring(hexData.length() - 4);
        Channel channel = new Channel();
        channel.setInOrOut(DeviceConstants.channelType.OUT.getCode());
        channel.setChannelNo(channelNo);
        channel.setChannelList(lines);
        channel.setMute(NumberBaseConversionUtil.valueHexToValueTen(muteHex));
        channel.setVolume(Float.valueOf(String.valueOf(NumberBaseConversionUtil.valueHexToValueTenSign(volumeHex)))/100);
        updateDeviceInfo(group,channel);*/
    }

  /*  private void updateDeviceInfo(Integer group, Channel channel) {
        DeviceModelVo vo = (DeviceModelVo) ConcurrentHashMapUtil.get("deviceModel_"+group);
        if (vo != null){
            List<Channel> channels = vo.getChannels();
            if (CollectionUtils.isEmpty(channels)){
                channels = new ArrayList<>();
            }
            for (int i = 0; i < channels.size(); i++){
                Channel c = channels.get(i);
                if (c.getChannelNo().equals(channel.getChannelNo()) && c.getInOrOut().equals(channel.getInOrOut())){
                    channels.remove(c);
                    break;
                }
            }
            channels.add(channel);
            vo.setChannels(channels);
            ConcurrentHashMapUtil.put("deviceModel_"+group,vo,30000);
        }
    }*/

    /*  private Line getLine(int i, String hexData) {
          Line line = new Line();
          int index = i * 14;
          String type = hexData.substring(2 + index, 4 + index);
          String ferquencyHex = hexData.substring(4 + index, 8 + index);
          String qHex = hexData.substring(8 + index, 12 + index);
          String gainHex = hexData.substring(12 + index, 16 + index);
          line.setNo(i);
          line.setFrequency(NumberBaseConversionUtil.valueHexToValueTen(ferquencyHex));
          line.setQ(Float.valueOf(String.valueOf(NumberBaseConversionUtil.valueHexToValueTen(qHex)))/100);
          line.setGain(Float.valueOf(String.valueOf(NumberBaseConversionUtil.valueHexToValueTenSign(gainHex)))/100);
          return line;
      }
  */
    private void deviceInputInfo(Integer group, String hexData) {
//        System.out.println("hexData-"+hexData);
        String channelNoHex = hexData.substring(0, 2);
        Integer channelNo = NumberBaseConversionUtil.valueHexToValueTen(channelNoHex);
      /*  List<Line> lines = new ArrayList<>();
        for (int i = 0; i < 15; i++){
            Line line = getLine(i,hexData);
            lines.add(line);
        }*/
        String muteHex = hexData.substring(hexData.length() - 16, hexData.length() - 14);
        String volumeHex = hexData.substring(hexData.length() - 14, hexData.length() - 10);
        String highHex = hexData.substring(hexData.length() - 10, hexData.length() - 6);
        String lowHex = hexData.substring(hexData.length() - 6, hexData.length() - 2);
        String swithHex = hexData.substring(hexData.length() - 2);
      /*  Channel channel = new Channel();
        channel.setInOrOut(DeviceConstants.channelType.IN.getCode());
        channel.setChannelNo(channelNo);
        channel.setChannelList(lines);
        channel.setHighCut(NumberBaseConversionUtil.valueHexToValueTen(highHex));
        channel.setLowCut(NumberBaseConversionUtil.valueHexToValueTen(lowHex));
        channel.setMute(NumberBaseConversionUtil.valueHexToValueTen(muteHex));
        channel.setVolume(Float.valueOf(String.valueOf(NumberBaseConversionUtil.valueHexToValueTenSign(volumeHex)))/100);
        channel.setRemote(NumberBaseConversionUtil.valueHexToValueTen(swithHex));
        updateDeviceInfo(group,channel);*/
    }

    private void deviceStateInfo(Integer group, String hexData) {

    }

    private void deviceGroupInfo(String hexData) {
        String groupHex = hexData.substring(0, 4);
        Integer group = NumberBaseConversionUtil.valueHexToValueTen(groupHex);
        String macHex = hexData.substring(4, 16);
        String mac = macHex.substring(0, 2) + "-" + macHex.substring(2, 4) + "-" + macHex.substring(4, 6) + "-" + macHex.substring(6, 8) + "-" + macHex.substring(8, 10) + "-" + macHex.substring(10, 12);
        String ipHex = hexData.substring(16, 24);
        String ip = NumberBaseConversionUtil.valueHexToValueTen(ipHex.substring(0, 2)) + "." + NumberBaseConversionUtil.valueHexToValueTen(ipHex.substring(2, 4)) + "." + NumberBaseConversionUtil.valueHexToValueTen(ipHex.substring(4, 6)) + "." + NumberBaseConversionUtil.valueHexToValueTen(ipHex.substring(6, 8));
        String noHex = hexData.substring(24, 28);
        Integer no = NumberBaseConversionUtil.valueHexToValueTen(noHex);
        String basePortHex = hexData.substring(28);
        //  Integer basePort = NumberBaseConversionUtil.valueHexToValueTen(basePortHex);
//        上面是数据解析部分
//        下面是根据设备类型进行缓存数据更新

 /*       if (dType == DeviceConstants.deviceType.AUDIO_PROCESSING.getCode()) {
            Device d = new Device();
            d.setDeviceNo(no);
            d.setMac(mac);
            d.setGroup(group);
            d.setIp(ip);
            d.setBasePort(basePort);
            ConcurrentHashMapUtil.put("group_" + mac, d, 10000);

        }else {
            DeviceAudioSource deviceAudioSource = new DeviceAudioSource();
            deviceAudioSource.setIp(ip)
                    .setType(dType)
                    .setGroup(group)
                    .setMac(mac);
            ConcurrentHashMapUtil.put("audioGroup_" + mac, deviceAudioSource, 10000);
        }*/


    }

}
